package com.platform.framework.util.net.tool;

import com.platform.framework.util.net.httpvo.HttpProtocolHandler;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.List;

/**
 * 发送HTTP请求工具类
 * @author ly-liugaoyang
 * @create time 2016年9月3日
 */
@SuppressWarnings({"rawtypes"})
public class HttpUtil {
	
	private static Logger logger = Logger.getLogger(HttpUtil.class);
	
	public static String doHttps(String url, String xml) throws Exception,
			IOException {
//		logger.info("[HttpUtil.doHttps] url = [" + url + "], xml = [" + xml + "]");
//		HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
//		HttpRequest request = new HttpRequest(HttpResultType.STRING);
//		// 设置编码集
//		request.setCharset("utf-8");
//		request.setUrl(url);
//
//		HttpResponse response = httpProtocolHandler.execute(request, "", "",xml);
//		logger.info("[HttpUtil.doHttps] response = [" + response + "] ");
//		if (response == null) {
//			return null;
//		}
//		logger.info("[HttpUtil.doHttps] response.getResultString = [" + response.getStringResult() + "] ");
//		return response.getStringResult();
        HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
        String postXml = httpProtocolHandler.postXml(url, xml);
        return postXml;
    }
	
	/**
     * 通过GET方式发起http请求
     */
	public static String executeHttpGet (String requestUrl) {
		//创建默认的httpClient实例
        CloseableHttpClient httpClient = getHttpClient();
        try {
            //用get方法发送http请求
            HttpGet get = new HttpGet(requestUrl);
            logger.info("执行get请求:...."+get.getURI());
            CloseableHttpResponse httpResponse = null;
            //发送get请求
            httpResponse = httpClient.execute(get);
            //response实体
            HttpEntity entity = httpResponse.getEntity();
            if (null != entity){
                logger.info("响应状态码:"+ httpResponse.getStatusLine());
                logger.info("-------------------------------------------------");
                String result = EntityUtils.toString(entity);
                logger.info("响应内容:" + result);
                logger.info("-------------------------------------------------");                    
                return result;
            }
        } catch (Exception e) {
        	logger.error("http exception : " + e);
            e.printStackTrace();
        }
        finally{
            try{
                closeHttpClient(httpClient);
            } catch (IOException e){
                e.printStackTrace();
            }
        }
		return "{\"result\":\"error\"}";
	}
	
	private static CloseableHttpClient getHttpClient(){
        return HttpClients.createDefault();
    }
     
    private static void closeHttpClient(CloseableHttpClient client) throws IOException{
        if (client != null){
            client.close();
        }
    }
	
	/**
     * 获取本机Ip 
     *  
     *  通过 获取系统所有的networkInterface网络接口 然后遍历 每个网络下的InterfaceAddress组。
     *  获得符合 <code>InetAddress instanceof Inet4Address</code> 条件的一个IpV4地址
     * @return
     */
   public static String localIp(){
      String ip = null;
      Enumeration allNetInterfaces;
      try {
   	  allNetInterfaces = NetworkInterface.getNetworkInterfaces();            
         while (allNetInterfaces.hasMoreElements()) {
	           NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
	           List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
	           for (InterfaceAddress add : InterfaceAddress) {
	               InetAddress Ip = add.getAddress();
	               if (Ip != null && Ip instanceof Inet4Address) {
	            	  ip = Ip.getHostAddress();
	               }
	           }
          }
       } catch (SocketException e) {
          logger.warn("获取本机Ip失败:异常信息:"+e.getMessage());
       }
       return ip;
   }
   
   
   public static void main(String[] args) {
	   String url = "http://weixin.dongfeng-nissan.com.cn/lyindex.php?g=Home&a=BookingMaintain&m=notify&orderNo=797983326475661312&payResult=2&sign=8271db0ebefec06fafd677a8f961344b";
	   executeHttpGet(url);
   }
}
